package com.wzx;


import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.Headers;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import com.wzx.basics.config.ConstantConfig;
import springfox.documentation.swagger.readers.operation.ResponseHeaders;

import java.io.File;
import java.net.URL;
import java.util.Date;

public class Download {


    public static void main(String[] args) throws Exception {
//        String key = "images/小狗.jpg";
//        String download = download(key);
//        System.out.println(download);
//        String urls = "https://wzx-1316381991.cos.ap-guangzhou.myqcloud.com/images/%E5%B0%8F%E7%8B%97.jpg?attname=&response-content-type=application/octet-stream";
//        String[] keys = urls.split("myqcloud.com");
        COSClient cosClient = createCOSClient();
        ObjectMetadata objectMetadata = cosClient.getObjectMetadata(ConstantConfig.BUCKET_NAME, "images/dog.jpg");


    }
    /**
     * 生成预下载  限速
     * */
    public static String download(String key){
        COSClient cosClient = createCOSClient();
        GeneratePresignedUrlRequest req =
                new GeneratePresignedUrlRequest(ConstantConfig.BUCKET_NAME, key, HttpMethodName.GET);
        // 填写本次请求的参数
        // 设定限速值，这里限速10M/s
        req.addRequestParameter("x-cos-traffic-limit", "8388608");
        req.addRequestParameter("response-content-disposition","attachment");
        // 填写本次请求的头部。Host 必填
        req.putCustomRequestHeader(Headers.HOST,
                cosClient.getClientConfig().getEndpointBuilder().buildGeneralApiEndpoint(ConstantConfig.BUCKET_NAME));
        URL url = cosClient.generatePresignedUrl(req);
        cosClient.shutdown();
        return url.toString();
        }

    /**
     * 创建COS客户端
     * @return
     */
    public static COSClient createCOSClient(){
        // 1 初始化用户身份信息(secretId, secretKey) 这里填你自己的
        COSCredentials cred = new BasicCOSCredentials(ConstantConfig.ACCESS_KEY_ID, ConstantConfig.ACCESS_KEY_SECRET);
        ClientConfig clientConfig = new ClientConfig(new Region(ConstantConfig.END_POINT));
        // 如果要获取 https 的 url 则在此设置，否则默认获取的是 http url
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 3 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        return cosclient;
    }

}
